<?php 
namespace App\Http\Controllers\TongGaoApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use App\Models\Mysql\tonggao\term;

use Excel;
use App\Http\Controllers\TongGaoApi\ExcelActionController;
use App\Http\Controllers\TongGaoApi\WordActionController;

class BibController extends Controller
{	
	const ROUTE_PREFIX = '/api/*';
	protected $request;
	protected $curTime;
	protected $debug;
	private $option=1; //1: book4 style; 
	/*
	参考文档
	1、https://www.jianshu.com/p/84ef90964304
	2、https://laravel-excel.maatwebsite.nl/docs/3.0/getting-started/basics
	*/

	public function	initWordInfo(&$dFSA,&$iFSA,&$textArray,&$FSA,&$bibCount){
		$dFSA=array('name' => 'Cambria', 'size' => 11, 'italic'=>false);
		$iFSA=array('name' => 'Cambria', 'size' => 11, 'italic'=>true);

		$textArray = array();
		$FSA = array();
		$bibCount = 0;
	}
	
	public function readCellData($desc, &$cellData, $tableFileName, $sheetName, &$header, &$colIndex, $book){	

		echo "begin to read $desc table</br>";
		$cellData = [];
		if (!empty($tableFileName)){
			Excel::load($tableFileName, function($reader) use ($desc,&$cellData,$sheetName) {
				//$reader = $reader->getSheet($PESheetIndex);
				$sheetIndex = ExcelActionController::getExcelSheetIndexBySheetName($reader,$sheetName);
				if ($sheetIndex===false){
					echo "$desc Table does not have the required sheet $sheetName</br>";
					exit;
				}
				echo "$desc table sheetIndex=$sheetIndex</br>";
				$reader = $reader->getSheet($sheetIndex);
				$cellData = $reader->toArray();
			});
			$this::trimCellData($cellData);			
			$header = $cellData[0];
			if ($desc=="PE")
				$this::setPEColIndex($colIndex,$header,$book);
			elseif($desc=="Bib")
				$this::setBibColIndex($colIndex,$header,$book);
			else
				$this::setChnBibColIndex($colIndex,$header,$book);
			//var_dump($colIndex);
		}
	}		
	
	public function genBib(){
		$bookArray = array(5);
		
		$this::initWordInfo($dFSA,$iFSA,$textArray,$FSA,$bibCount);
		
		foreach($bookArray as $book){
			$outputWordFile = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\0817\\bib_$book.docx");
			
			//引文表相关信息
			switch($book){
				case 5:
				case 7:
				case 8:
					$PETableFileName = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\0817\\book{$book}_引文文献-20180819b-chap01.xlsx");
					$PESheetName = "ALL";
					$PEStartRowIndex=1;
			}

			//英文文献表相关信息
			$Bib_BIB_ID_ColIndex = 0;
			$Bib_BIB_Type_ColIndex = 1;
			$BibStartRowIndex=1;
			$BibSheetName = "译著";
			switch($book){
				case 5:
					$BibTableFileName = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\0817\\英文经论书目汇总20180819b.xls");
					break;
				case 7:
				case 8:
					$BibTableFileName = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\0718\\7-8册英文经论书目汇总20180716.xls");
					$BibTableFileName = "";
					break;
			}
			//中文文献表相关信息
			$ChnBibSheetIndex = 0;
			$ChnBib_ChnBIB_ID_ColIndex = 0;
			$ChnBibStartRowIndex=1;
			$ChnBibEleNames = array('CBIB_ID','CBETA_CHNBOOKNAME','CBETA_BOOKNO','CBETA_SUTRANO','EnglishBookName','SanskritBookName','ChineseBookName','AuthorNameInEnglish','URL');
			switch($book){
				case 5:
					$ChnBibTableFileName = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\0817\\文集4-8册经论书目列表-Sherry-v5.xlsx");
					//$ChnBibSheetName = iconv('UTF-8', 'GBK', "第{$book}册中文文献");
					$ChnBibSheetName = "第{$book}册中文文献";
					echo "{$book}</br>";
					echo "第{$book}册中文文献</br>";
					break;
			}

			$this::readCellData("PE", $PECellData, $PETableFileName, $PESheetName, $PEHeader, $PEColIndex, $book);
			$this::readCellData("Bib", $BibCellData, $BibTableFileName, $BibSheetName, $BibHeader, $BibColIndex, $book);
			$this::readCellData("ChnBib", $ChnBibCellData, $ChnBibTableFileName, $ChnBibSheetName, $ChnBibHeader, $ChnBibColIndex, $book);
			var_dump($ChnBibColIndex);
			//generate Bibliography
			$textArray[$bibCount][0] = "Bibliography";
			$FSA[$bibCount][0] = array('name' => 'Tahoma', 'size' => 30, 'italic'=>false);
			$bibCount++;

			if (!empty($ChnBibTableFileName)){
				//generate Scriptural Sources in Chinese
				echo "generate Scriptural Sources in Chinese</br>";
				$textArray[$bibCount][0] = "Scriptural Sources in Chinese";
				$FSA[$bibCount][0] = array('name' => 'Tahoma', 'size' => 20, 'italic'=>false);
				$bibCount++;
			
				foreach($ChnBibCellData as $ChnBibRowIndex=>$ChnBibRow){
					if ($ChnBibRowIndex<$ChnBibStartRowIndex)
						continue;					
					//$data = $this::genBibSourceChineseItemData($ChnBibRow,$ChnBibColIndex);
					$data = $this::genData($ChnBibRow,$ChnBibColIndex,$ChnBibEleNames);
					$data['CBETA_CHNBOOKNAME'] = $this::stripBookNameMark($data['CBETA_CHNBOOKNAME']);
					$this::genBibSourceChineseItemWord($data,$textArray,$FSA,$bibCount,$dFSA,$iFSA,"","CBETASUTRA_ONLY");
				}
				
				//generate Other Sources in Chinese
				echo "generate Other Sources in Chinese</br>";
				$textArray[$bibCount][0] = "Other Sources in Chinese";
				$FSA[$bibCount][0] = array('name' => 'Tahoma', 'size' => 20, 'italic'=>false);
				$bibCount++;
			
				foreach($ChnBibCellData as $ChnBibRowIndex=>$ChnBibRow){
					if ($ChnBibRowIndex<$ChnBibStartRowIndex)
						continue;					
					//$data = $this::genBibSourceChineseItemData($ChnBibRow,$ChnBibColIndex);
					//var_dump($data);
					$data = $this::genData($ChnBibRow,$ChnBibColIndex,$ChnBibEleNames);
					$data['CBETA_CHNBOOKNAME'] = $this::stripBookNameMark($data['CBETA_CHNBOOKNAME']);
					$this::genBibSourceChineseItemWord($data,$textArray,$FSA,$bibCount,$dFSA,$iFSA,"","OTHER_ONLY");
				}
				
			}//end of if
			
			//generate Sources in English
			if (!empty($ChnBibTableFileName)){
				$textArray[$bibCount][0] = "Sources in English";
				$FSA[$bibCount][0] = array('name' => 'Tahoma', 'size' => 20, 'italic'=>false);
				$bibCount++;
			
				echo "generate English source</br>";
				foreach($BibCellData as $BibRowIndex=>$BibRow){
					if ($BibRowIndex<$BibStartRowIndex)
						continue;
					$bibType = $BibRow[$BibColIndex['Type']];
					$bibType = $this::getBibTypeCode($bibType);
					//var_dump($BibRow);
					//echo "Bib_BIB_Type_ColIndex=$Bib_BIB_Type_ColIndex</br>";
					//echo "bibType=$bibType";
					$data = $this::genBibSourceEnglishItemData($bibType,$BibRow,$BibColIndex,array(),array());
					//echo "data is done</br>";
					$this::genBibSourceEnglishItemWord($bibType,$data,$textArray,$FSA,$bibCount,$BibColIndex,"curPE_NO NOT NEEDED",$dFSA,$iFSA,false,false);
					//$this::genBibSourceEnglishItemWord();
				}
			}//end of if for generate  Sources in English

			if (!empty($ChnBibTableFileName) && !empty($BibTableFileName) && !empty($ChnBibTableFileName)){
				echo "generate footnote</br>";
				$textArray[$bibCount][0] = "FootNotes";
				$FSA[$bibCount][0] = array('name' => 'Tahoma', 'size' => 30, 'italic'=>false);
				$bibCount++;
				
				foreach($PECellData as $PERowIndex=>$PERow){
					if ($PERowIndex<$PEStartRowIndex)
						continue;					
					$curPE_NO = $PERow[$PEColIndex['PE-NO']];
					$curSelfTran = $PERow[$PEColIndex['SelfTran']];
					$curCOPY = $PERow[$PEColIndex['COPY']];
					$curRevise = $PERow[$PEColIndex['Revise']];
					$curCBIB_ID = $PERow[$PEColIndex['CBIB_ID']];
					$curEBIB_ID = $PERow[$PEColIndex['EBIB_ID']];
					if (empty($curPE_NO))
						continue;
					if ($curSelfTran==1){
						if (empty($curCBIB_ID)){
							echo "Generate footnote error: $curPE_NO CBIB_ID empty at row $PERowIndex</br>";
							continue;
						}
						$ChnBibRowIndex = $this::searchInAColumnOfCellData($ChnBibCellData,$ChnBibColIndex['CBIB_ID'] ,$curCBIB_ID);
						if ($ChnBibRowIndex===false){
							echo "Generate footnote error: $curPE_NO CBIB_ID $curCBIB_ID not found at row $PERowIndex</br>";
							continue;
						}
						$ChnBibRow = $ChnBibCellData[$ChnBibRowIndex];
						$data = $this::genBibSourceChineseItemData($ChnBibRow,$ChnBibColIndex);
						$this::genBibSourceChineseItemWord($data,$textArray,$FSA,$bibCount,$dFSA,$iFSA,$curPE_NO,"ANY");
						$this::genBibSourceEnglishItemWord("",$data,$textArray,$FSA,$bibCount,$ChnBibColIndex,$curPE_NO,$dFSA,$iFSA,true,$curRevise);
							
					}else{
						if (empty($curCBIB_ID) || empty($curEBIB_ID)){
							echo "Generate footnote error: $curPE_NO CBIB_ID or EBIB_ID empty at row $PERowIndex</br>";
							continue;
						}
						$ChnBibRowIndex = $this::searchInAColumnOfCellData($ChnBibCellData,$ChnBibColIndex['CBIB_ID'] ,$curCBIB_ID);
						$EngBibRowIndex = $this::searchInAColumnOfCellData($BibCellData,$BibColIndex['EBIB_ID'] ,$curEBIB_ID);
						if (($ChnBibRowIndex===false) ){
							echo "Generate footnote error: $curPE_NO CBIB_ID $curCBIB_ID not found at row ".(string)($PERowIndex+1)."</br>";//echo "Generate footnote error: EBIB_ID $curEBIB_ID not found at row $PERowIndex</br>";
							continue;
						}
						if (($EngBibRowIndex===false)){
							echo "Generate footnote error: $curPE_NO EBIB_ID $curEBIB_ID not found at row ".(string)($PERowIndex+1)."</br>";//echo "Generate footnote error: EBIB_ID $curEBIB_ID not found at row $PERowIndex</br>";
							continue;
						}
												
						$BibRow = $BibCellData[$EngBibRowIndex];
						$bibType = $BibRow[$BibColIndex['Type']];
						$bibType = $this::getBibTypeCode($bibType);
						
						$mixedBibRow = $BibRow;
						$ChnBibRow = $ChnBibCellData[$ChnBibRowIndex];
						if (strtoupper(mb_substr($ChnBibRow[$ChnBibColIndex['CBETA_CHNBOOKNAME']],0,5))<>"OTHER"){
							$mixedBibRow[$BibColIndex['CBETA_CHNBOOKNAME']] = $ChnBibRow[$ChnBibColIndex['CBETA_CHNBOOKNAME']] ;
							$mixedBibRow[$BibColIndex['CBETA_BOOKNO']] = $ChnBibRow[$ChnBibColIndex['CBETA_BOOKNO']];
							$mixedBibRow[$BibColIndex['CBETA_SUTRANO']] = $ChnBibRow[$ChnBibColIndex['CBETA_SUTRANO']];
						}else{
							$mixedBibRow[$BibColIndex['CBETA_CHNBOOKNAME']] = $ChnBibRow[$ChnBibColIndex['ChineseBookName']];
							//echo "$curPE_NO</br>";
							//echo "{$mixedBibRow[$BibColIndex['CBETA_CHNBOOKNAME']]}</br>";
							//var_dump($mixedBibRow);
						}
						
						$data = $this::genBibSourceEnglishItemData($bibType,$mixedBibRow,$BibColIndex,$PERow,$PEColIndex);
						//echo "data is done</br>";
						$this::genBibSourceEnglishItemWord($bibType,$data,$textArray,$FSA,$bibCount,$BibColIndex,$curPE_NO,$dFSA,$iFSA,true,$curRevise);
					}
				}
			}
			
//			WordActionController::exportWord_01($outputWordFile,array("hi","text"));
			WordActionController::exportWord_01($outputWordFile,$textArray,$FSA);
		}
	}
	
	public function trimCellData(&$cellData){
		foreach($cellData as $i=>$rowData){
			foreach($rowData as $j=>$oneCellData){
				$oneCellData = trim($oneCellData);
				if (in_array($oneCellData,array("NA","#N/A","0"))){
					//echo "oneCellData=$oneCellData</br>";
					//echo "{$cellData[$i][$j]}</br>";
					$oneCellData = "";
				}
				$cellData[$i][$j]=$oneCellData;
				//echo "{$cellData[$i][$j]}</br>";
			}
		}
	}

	public function searchInAColumnOfCellData(&$cellData,$colIndex,$needle){
		foreach($cellData as $rowIndex=>$rowData){
			if (trim($rowData[$colIndex])==$needle)
				return $rowIndex;
		}
		return false;
	}
	
	public function setPEColIndex(&$PEColIndex,&$PEHeader,$book){
		$PEColIndex['PE-NO']	= getColIndex($PEHeader,"PE-NO");
		$PEColIndex['SelfTran']	= getColIndex($PEHeader,"自译标志");
		$PEColIndex['COPY']		= getColIndex($PEHeader,"引用标志");
		$PEColIndex['Revise']	= getColIndex($PEHeader,array("引文是否有改动","Y/N"));
		$PEColIndex['CBIB_ID']	= getColIndex($PEHeader,"CBIB_ID");
		$PEColIndex['EBIB_ID']	= getColIndex($PEHeader,"BIB_ID");
		$PEColIndex['VolumeNo']	= getColIndex($PEHeader,"译文所在卷（如英译广论有3本，需要明确是第几本）");
		$PEColIndex['PageNo']	= getColIndex($PEHeader,"所在页");
	}
	
	public function setBibColIndex(&$BibColIndex,&$BibHeader,$book){
		switch($book){
			case 4:
			case 5:
			case 6:
			case 7:
			case 8:			
				$BibColIndex['EBIB_ID']    			= getColIndex($BibHeader,"BIB_ID"); //0
				$BibColIndex['Type']    			= getColIndex($BibHeader,"种类"); //0
				$BibColIndex['Translator']         	= getColIndex($BibHeader,array("作者","或译者团队"));//15
				$BibColIndex['EnglishBookName']    	= getColIndex($BibHeader,"书/文摘英文名"); //12
				$BibColIndex['SanskritBookName']   	= getColIndex($BibHeader,"书/文摘梵文名"); //13
				$BibColIndex['AuthorNameInEnglish']	= getColIndex($BibHeader,"造者英文");// 7;
				$BibColIndex['CBETA_CHNBOOKNAME']   = getColIndex($BibHeader,"CBETA经论名中文");// 4;
				$BibColIndex['CBETA_BOOKNO']        = getColIndex($BibHeader,"CBETA册号");// 2;
				$BibColIndex['CBETA_SUTRANO']       = getColIndex($BibHeader,"CBETA经号");// 3;
				$BibColIndex['MiddleLanguage']    	= getColIndex($BibHeader,"Translated from 语种");//10;
				$BibColIndex['MiddleLanguageTranslator'] = getColIndex($BibHeader,"Translated from 译者");//11;
				$BibColIndex['PublishHouse']       	= getColIndex($BibHeader,"出版者");//17;
				$BibColIndex['PublishCountry']    	= getColIndex($BibHeader,"出版国家或地区");//16;
				$BibColIndex['PublishTime']       	= getColIndex($BibHeader,"出版时间");//18;
				$BibColIndex['URL']               	= getColIndex($BibHeader,"网站");//26;
				break;
		}
	}
	
	public function setChnBibColIndex(&$ChnBibColIndex,$ChnBibHeader){
		$ChnBibColIndex['CBIB_ID'] 			 = getColIndex($ChnBibHeader,"CBIB_ID"); //0
		$ChnBibColIndex['CBETA_CHNBOOKNAME'] = getColIndex($ChnBibHeader,"CBETA经论名中文");
		$ChnBibColIndex['CBETA_BOOKNO'] = getColIndex($ChnBibHeader,"CBETA册号");
		$ChnBibColIndex['CBETA_SUTRANO'] = getColIndex($ChnBibHeader,"CBETA经号");
		//$ChnBibColIndex['CHN_BIB_ID'] =  getColIndex($ChnBibHeader,"CHN_BIB_ID");
		$ChnBibColIndex['EnglishBookName'] =  getColIndex($ChnBibHeader,"JJC English");//"文集经论英文书名"
		$ChnBibColIndex['SanskritBookName'] =  getColIndex($ChnBibHeader,"JJC Sanskrit");//"文集经论英文书名（梵文）"
		
		$ChnBibColIndex['ChineseBookName'] =  getColIndex($ChnBibHeader,"CBIB_ID");
		$ChnBibColIndex['AuthorNameInEnglish']=  getColIndex($ChnBibHeader,"造者");
		$ChnBibColIndex['URL']=  getColIndex($ChnBibHeader,"备注");
	}
	
	public function getBibTypeByBibId(&$BibCellData, $Bib_BIB_ID_ColIndex, $Bib_BIB_Type_ColIndex, $curPE_BIB_ID){
		$found = false;
		foreach($BibCellData as $BibRow){
			if ($BibRow[$Bib_BIB_ID_ColIndex]<>$curPE_BIB_ID)
				continue;
			$bibType = trim($BibRow[$Bib_BIB_Type_ColIndex]);
			echo "bibType=$bibType</br>";
			$bibType = $this::getBibTypeCode($bibType);
			echo "$bibType</br>";
			$found=true;
			break;
		}
		if ($found==false)
			return array(false,array());
		else
			return array($bibType,$BibRow);
	}
	
	public function getBibTypeCode($bibType){
		$bibTypeCode = false;
		switch($bibType){
			case "译著":
				$bibTypeCode = "TRANCOPY";
				break;
			case "论文":
				$bibTypeCode = "THESIS";
				break;
			case "期刊":
				$bibTypeCode = "JOURNAL";
				break;
			case "网址":
			case "网站":
				$bibTypeCode = "WEB";
				break;
		}
		return $bibTypeCode;
	}

	public function genBibSourceEnglishItemData($bibType,$BibRow,$BibColIndex,$PERow,$PEColIndex){
		$data = array();
		switch($bibType){
			case "TRANCOPY":
			case "WEB":
			
				$data['Translator'] = $BibRow[$BibColIndex['Translator']];
				$data['EnglishBookName'] = $BibRow[$BibColIndex['EnglishBookName']];
				$data['SanskritBookName'] = $BibRow[$BibColIndex['SanskritBookName']];
				$data['AuthorNameInEnglish'] = $BibRow[$BibColIndex['AuthorNameInEnglish']];
				$data['CBETA_CHNBOOKNAME'] = $BibRow[$BibColIndex['CBETA_CHNBOOKNAME']];
				$data['CBETA_BOOKNO'] = $BibRow[$BibColIndex['CBETA_BOOKNO']];
				$data['CBETA_SUTRANO'] = $BibRow[$BibColIndex['CBETA_SUTRANO']];
				$data['MiddleLanguage'] = $BibRow[$BibColIndex['MiddleLanguage']];
				$data['MiddleLanguageTranslator'] = $BibRow[$BibColIndex['MiddleLanguageTranslator']];
				$data['PublishHouse'] = $BibRow[$BibColIndex['PublishHouse']];
				$data['PublishCountry'] = $BibRow[$BibColIndex['PublishCountry']];
				$data['PublishTime'] = $BibRow[$BibColIndex['PublishTime']];
				$data['URL'] = $BibRow[$BibColIndex['URL']];
				if (!empty($PERow)){
					$data['VolumeNo'] = $PERow[$PEColIndex['VolumeNo']];
					$data['PageNo'] = $PERow[$PEColIndex['PageNo']];
				}
				
				//construct AdditionalBookName
				/*
				$data['AdditionalBookName'] = "";
				if (!empty($data['CBETA_CHNBOOKNAME']) || !empty($data['SanskritBookName'])){
					$data['AdditionalBookName'] .= "(";
					if (!empty($data['CBETA_CHNBOOKNAME']))
						$data['AdditionalBookName'] .= "{$data['CBETA_CHNBOOKNAME']}";
					if (!empty($data['SanskritBookName'])){
						$data['AdditionalBookName'] .= ", {$data['SanskritBookName']}";
						if (!empty($data['AuthorNameInEnglish'])){
							$data['AdditionalBookName'] .= " by {$data['AuthorNameInEnglish']}";
						}
					}
					if (!empty($data['CBETA_BOOKNO']))
						$data['AdditionalBookName'] .= ", {$data['CBETA_BOOKNO']}";
					if (!empty($data['CBETA_SUTRANO']))
						$data['AdditionalBookName'] .= ", No. {$data['CBETA_SUTRANO']}";
					$data['AdditionalBookName'] .= "). ";
				}
				*/
				
				//construct MiddleLanguageInfo
				$data['MiddleLanguageInfo'] = "";
				if (!empty($data['MiddleLanguage'])){
					if (!empty($data['MiddleLanguageTranslator']))
						$data['MiddleLanguageInfo'] .= "{$data['MiddleLanguageTranslator']}, ";
					$data['MiddleLanguageInfo'] .= "Translated from the {$data['MiddleLanguage']}";
					//if (!empty($data['Translator'])){
					//	
					//}
				}
								
				//construct PublishInfo
				$data['PublishInfo'] = "";
				if (!empty($data['PublishHouse']) || !empty($data['PublishCountry']) || !empty($data['PublishTime'])){
					if (!empty($data['PublishHouse'])){
						$data['PublishInfo'] .= "{$data['PublishHouse']}";
						if (!empty($data['PublishCountry']) || !empty($data['PublishTime']))
							$data['PublishInfo'] .= ", ";
					}
					if (!empty($data['PublishCountry'])){
						$data['PublishInfo'] .= "{$data['PublishCountry']}";
						if (!empty($data['PublishTime']))
							$data['PublishInfo'] .= ", ";
					}
					if (!empty($data['PublishTime']))
						$data['PublishInfo'] .= "{$data['PublishTime']}";
				}
				
				break;
		}
		return $data;
	}
	
	public function genBibSourceEnglishItemWord($bibType,$data,&$textArray,&$FSA,&$bibCount,$BibColIndex,$curPE_NO,$dFSA,$iFSA,$perItem,$curRevise){
		//if ($curPE_NO=="A1.1")	echo "I am in word</br>";
		//if ($curPE_NO=="A1.1")	var_dump($data);
		switch($bibType){
			case "TRANCOPY":
			case "WEB":
			case "":
				$curTextArray = array();
				$curFSA = array();
				$BibOutput = "";			
				
				if ($curPE_NO!="curPE_NO NOT NEEDED")
					$this::addPhraseToWord($curPE_NO." ", $dFSA, $BibOutput,$curTextArray,$curFSA);				
				
				if ($perItem && strtoupper(mb_substr($curRevise,0,1))=="Y")
					$this::addPhraseToWord("Revised from ", $dFSA, $BibOutput,$curTextArray,$curFSA);				
				
				//determine $data['LastField']
				$data['LastField'] = "Page";
				if ( empty($data['PublishInfo']) && empty($data['URL']) && empty($data['VolumeNo']) && empty($data['PageNo']) ){
					if (!empty($data['MiddleLanguageInfo']))
						$data['LastField'] = 'MiddleLanguageInfo';
					else{
						if (!empty($data['CBETA_CHNBOOKNAME']))
							$data['LastField'] = 'CBETA_CHNBOOKNAME';
						else
							$data['LastField'] = 'EnglishBookName';
					}
				}
				$data['LastFieldButVP'] = "";
				if ($perItem){
					if ( empty($data['PublishInfo']) && empty($data['URL']) ){
						if (!empty($data['MiddleLanguageInfo']))
							$data['LastFieldButVP'] = 'MiddleLanguageInfo';
						else{
							if (!empty($data['CBETA_CHNBOOKNAME']))
								$data['LastFieldButVP'] = 'CBETA_CHNBOOKNAME';
							else
								$data['LastFieldButVP'] = 'EnglishBookName';
						}
					}
				}
				
				if (!empty($data['Translator']))
					$this::addPhraseToWord($data['Translator'].", ", $dFSA, $BibOutput,$curTextArray,$curFSA);
				if (!empty($data['EnglishBookName'])){
					$this::addPhraseToWord($data['EnglishBookName'], $iFSA, $BibOutput,$curTextArray,$curFSA);
					if (   ((!$perItem) && ($data['LastField']<>'EnglishBookName'))
						|| (($perItem) && ($data['LastFieldButVP']<>'EnglishBookName'))
					   )
						$this::addPhraseToWord(", ", $dFSA, $BibOutput,$curTextArray,$curFSA);
				}

				//if (!empty($data['AdditionalBookName'])){
				//	$this::addPhraseToWord($data['AdditionalBookName'], $dFSA, $BibOutput,$curTextArray,$curFSA);
				//}
				//if ($curPE_NO=="A1.1")	echo "I am before printing chinese book name</br>";
				if (!empty($data['CBETA_CHNBOOKNAME']) || !empty($data['SanskritBookName'])){
					//if ($curPE_NO=="A1.1")	var_dump($data);
					if (!$perItem)
						$this::addPhraseToWord("(", $dFSA, $BibOutput,$curTextArray,$curFSA);
					if (!empty($data['CBETA_CHNBOOKNAME']))
						$this::addPhraseToWord("{$data['CBETA_CHNBOOKNAME']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
					if (!empty($data['SanskritBookName'])){
						$this::addPhraseToWord(", {$data['SanskritBookName']}", $iFSA, $BibOutput,$curTextArray,$curFSA);
						if (!empty($data['AuthorNameInEnglish'])){
							$this::addPhraseToWord(" by {$data['AuthorNameInEnglish']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
						}
					}
					if (!empty($data['CBETA_BOOKNO']))
						$this::addPhraseToWord(", {$data['CBETA_BOOKNO']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
					if (!empty($data['CBETA_SUTRANO']))
						$this::addPhraseToWord(", No. {$data['CBETA_SUTRANO']}, 2016/09/28 version", $dFSA, $BibOutput,$curTextArray,$curFSA);
					if (!$perItem)
						$this::addPhraseToWord(")", $dFSA, $BibOutput,$curTextArray,$curFSA);
					if (   ((!$perItem) && ($data['LastField']<>'CBETA_CHNBOOKNAME'))
						|| (($perItem) && ($data['LastFieldButVP']<>'CBETA_CHNBOOKNAME'))
					   )
						$this::addPhraseToWord(". ", $dFSA, $BibOutput,$curTextArray,$curFSA);
				}
				
				if (!empty($data['MiddleLanguageInfo'])){
					$this::addPhraseToWord($data['MiddleLanguageInfo'], $dFSA, $BibOutput,$curTextArray,$curFSA);
					if (   ((!$perItem) && ($data['LastField']<>'MiddleLanguageInfo'))
						|| (($perItem) && ($data['LastFieldButVP']<>'MiddleLanguageInfo'))
					   )
						$this::addPhraseToWord(", ", $dFSA, $BibOutput,$curTextArray,$curFSA);
				}
				if ($bibType=="TRANCOPY"){
					if (!empty($data['PublishInfo']))
						$this::addPhraseToWord($data['PublishInfo'], $dFSA, $BibOutput,$curTextArray,$curFSA);
					//else
					//	$this::addPhraseToWord("错误-译著必需有出版信息", $iFSA, $BibOutput,$curTextArray,$curFSA);
				}else{
					if (!empty($data['URL']))
						$this::addPhraseToWord("  Available on line at {$data['URL']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
				}
				
				if ($perItem){
					//echo "perItem is true</br>";
					//var_dump($data);
					if (!empty($data['VolumeNo'])){
						$this::addPhraseToWord(". Vol {$data['VolumeNo']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
					}
					if (!empty($data['PageNo'])){
						$this::addPhraseToWord(". Page {$data['PageNo']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
					}
				}
				
				$this::addPhraseToWord(". ", $dFSA, $BibOutput,$curTextArray,$curFSA);
				
				$textArray[$bibCount] = $curTextArray;
				$FSA[$bibCount] = $curFSA;
				$bibCount++;
				break;
	
			default:
				$errorMessage = "需要手工处理，原因：$bibType 类型不支持";
				$BibOutput = $errorMessage;
				$curTextArray []= $errorMessage;
				$curFSA []= $dFSA; 			
				$textArray[$bibCount] = $curTextArray;
				$FSA[$bibCount] = $curFSA;
				$bibCount++;
				break;				
		}
	}

	public function genBibSourceChineseItemData($ChnBibRow,$ChnBibColIndex){
	
		$data['CBIB_ID'] = $ChnBibRow[$ChnBibColIndex['CBIB_ID']];
		$data['CBETA_CHNBOOKNAME'] = $ChnBibRow[$ChnBibColIndex['CBETA_CHNBOOKNAME']];
		$data['CBETA_CHNBOOKNAME'] = str_replace("《","",$data['CBETA_CHNBOOKNAME']);
		$data['CBETA_CHNBOOKNAME'] = str_replace("》","",$data['CBETA_CHNBOOKNAME']);
		$data['CBETA_BOOKNO'] =  $ChnBibRow[$ChnBibColIndex['CBETA_BOOKNO']];
		$data['CBETA_SUTRANO'] = $ChnBibRow[$ChnBibColIndex['CBETA_SUTRANO']];
		$data['EnglishBookName'] =  $ChnBibRow[$ChnBibColIndex['EnglishBookName']];				
		$data['SanskritBookName'] =  $ChnBibRow[$ChnBibColIndex['SanskritBookName']];
		$data['ChineseBookName'] =  $ChnBibRow[$ChnBibColIndex['ChineseBookName']];		
		$data['AuthorNameInEnglish'] =  $ChnBibRow[$ChnBibColIndex['AuthorNameInEnglish']];
		$data['URL'] =  $ChnBibRow[$ChnBibColIndex['URL']];
		return $data;
	}
	
	public function genData($src, $index, $eleNames){
		$data = array();
		foreach($eleNames as $eleName)
			$data[$eleName] = (array_key_exists($eleName,$index)) ? $src[$index[$eleName]] : false;
		return $data;
	}
	
	public function stripBookNameMark($str){
		return str_replace("》","",str_replace("《","",$str));
	}

	public function genBibSourceChineseItemWord($data,&$textArray,&$FSA,&$bibCount,$dFSA,$iFSA,$curPE_NO,$outputType){
		
		$curTextArray = array();
		$curFSA = array();
		$BibOutput = "";
		
		/*
		if (empty($data['CBETA_CHNBOOKNAME'])){
			$errorMessage = "需要手工处理，原因：CBETA中文书名为空，可能属于中文文献里的其他";
			$this::addPhraseToWord($errorMessage, $dFSA, $BibOutput,$curTextArray,$curFSA);
			$textArray[$bibCount] = $curTextArray;
			$FSA[$bibCount] = $curFSA;
			$bibCount++;
			return;
		}*/		
		//echo "CBIB_ID={$data['CBIB_ID']}  CBETA_CHNBOOKNAME={$data['CBETA_CHNBOOKNAME']}</br>";

		//if ($data['CBETA_CHNBOOKNAME']=="Other")
			//var_dump($data);
		
		if ( (!empty($data['CBETA_CHNBOOKNAME']) && strtoupper(mb_substr($data['CBETA_CHNBOOKNAME'],0,5))<>"OTHER" && in_array($outputType,array("CBETASUTRA_ONLY","ANY"))) ||
			 (strtoupper(mb_substr($data['CBETA_CHNBOOKNAME'],0,5))=="OTHER" &&  in_array($outputType,array("OTHER_ONLY","ANY"))) )
		{
			if (!empty($curPE_NO)){
				$this::addPhraseToWord($curPE_NO." ", $dFSA, $BibOutput,$curTextArray,$curFSA);
			}
		}
		
		if (!empty($data['CBETA_CHNBOOKNAME']) && strtoupper(mb_substr($data['CBETA_CHNBOOKNAME'],0,5))<>"OTHER" && in_array($outputType,array("CBETASUTRA_ONLY","ANY"))){
		
			$this::addPhraseToWord("{$data['EnglishBookName']}, ", $iFSA, $BibOutput,$curTextArray,$curFSA);
			if (!empty($data['SanskritBookName'])){
				$this::addPhraseToWord("{$data['CBETA_CHNBOOKNAME']}, ", $dFSA, $BibOutput,$curTextArray,$curFSA);
				$this::addPhraseToWord("{$data['SanskritBookName']}", $iFSA, $BibOutput,$curTextArray,$curFSA);
			}else{
				$this::addPhraseToWord("{$data['CBETA_CHNBOOKNAME']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
			}
			$this::addPhraseToWord( ". ", $dFSA, $BibOutput,$curTextArray,$curFSA);
			$this::addPhraseToWord(" {$data['CBETA_BOOKNO']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
			$this::addPhraseToWord(", No.{$data['CBETA_SUTRANO']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
			$this::addPhraseToWord( ", 2016/09/28 version", $dFSA, $BibOutput,$curTextArray,$curFSA);
		}
		
		if ( strtoupper(mb_substr($data['CBETA_CHNBOOKNAME'],0,5))=="OTHER" &&  in_array($outputType,array("OTHER_ONLY","ANY")) ){
			//echo "other</br>";
			if (!empty($data['AuthorNameInEnglish']))
				$this::addPhraseToWord("{$data['AuthorNameInEnglish']}, ", $dFSA, $BibOutput,$curTextArray,$curFSA);
			if (!empty($data['EnglishBookName']))
				$this::addPhraseToWord("{$data['EnglishBookName']}, ", $iFSA, $BibOutput,$curTextArray,$curFSA);
			if (!empty($data['ChineseBookName']))
				$this::addPhraseToWord("{$data['ChineseBookName']}", $dFSA, $BibOutput,$curTextArray,$curFSA);	
			if (!empty($data['URL'])){
				$this::addPhraseToWord(".  Available on line at {$data['URL']}", $dFSA, $BibOutput,$curTextArray,$curFSA);
			}
		}
		
		if ( (!empty($data['CBETA_CHNBOOKNAME']) && strtoupper(mb_substr($data['CBETA_CHNBOOKNAME'],0,5))<>"OTHER" && in_array($outputType,array("CBETASUTRA_ONLY","ANY"))) ||
			 (strtoupper(mb_substr($data['CBETA_CHNBOOKNAME'],0,5))=="OTHER" &&  in_array($outputType,array("OTHER_ONLY","ANY")))	)
		{
			$this::addPhraseToWord(". ", $dFSA, $BibOutput,$curTextArray,$curFSA);
			$textArray[$bibCount] = $curTextArray;
			$FSA[$bibCount] = $curFSA;
			$bibCount++;		
		}
	}
	
	public function addPhraseToWord($phrase, $FSA, &$BibOutput,&$curTextArray,&$curFSA){
		$BibOutput = $phrase;
		$curTextArray []= $phrase;
		$curFSA []= $FSA; 			
	}
	
	public function testRTF(){
		$tableFileName = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\rtf.xlsx");;
		$sheetName = "Sheet1";
		$cellData=array();
		$desc="";
		Excel::load($tableFileName, function($reader) use ($desc,&$cellData,$sheetName) {
			//$reader = $reader->getSheet($PESheetIndex);
			$sheetIndex = ExcelActionController::getExcelSheetIndexBySheetName($reader,$sheetName);
			if ($sheetIndex===false){
				echo "$desc Table does not have the required sheet $sheetName</br>";
				exit;
			}
		/* regression
			echo "$desc table sheetIndex=$sheetIndex</br>";
			$reader = $reader->getSheet($sheetIndex);
			$cellData = $reader->toArray();
			var_dump($cellData);*/

			/**读取excel文件中的第一个工作表*/
			$currentSheet = $reader->getSheet(0);			
			/**取得最大的列号*/
			$allColumn = $currentSheet->getHighestColumn();
			/**取得一共有多少行*/
			$allRow = $currentSheet->getHighestRow();
			
			//循环读取每个单元格的内容。注意行从1开始，列从A开始
			for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){
				for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
					$addr = $colIndex.$rowIndex;
					$cell = $currentSheet->getCell($addr)->getValue();
					//var_dump($cell);
					if($cell instanceof PHPExcel_RichText){
					$rts = $cell->getRichTextElements();
					foreach($rts as $rt){
						//var_dump($rt);
						echo "<---text---></br>";
						var_dump($rt->getText());						
						echo "<---font---></br>";
						$font=$rt->getFont();
						var_dump($font);
					}
					}
					if($cell instanceof PHPExcel_RichText)     //富文本转换字符串
						var_dump($cell);//$cell = $cell->__toString();
						
					//echo $cell;
				
				}
			
			}
		});
	}
}
?>